#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim: set ts=4 sw=4 noet:
#
# $Id$

"""
HistoryProvider.py

Wraps a ComboBoxEntry with a file containing previous values.

It provides the facility to load() and update() the history.
"""

__version__ = "$Revision$"
# $URL$

import os

class HistoryProvider(object):
	LENGTH = 20
	def __init__(self, combo, filename, encoding="utf-8"):
		"""
		Takes a combo box and a filename.
		"""
		self._combo = combo
		self._filename = filename
		self._encoding = encoding
		self.load()

	def load(self):
		"""
		Loads the history into the combo.
		"""
		if not os.path.exists(self._filename):
			open(self._filename, "w")
		model = self._combo.get_model()
		model.clear()
		added = 0
		for line in open(self._filename, "r").xreadlines():
			line = line.strip().decode(self._encoding)
			model.set_value(model.append(), 0, line)
			added += 1
			if added == self.LENGTH:
				break
	
	def update(self):
		"""
		Adds the combo's active text to the history.
		"""
		model = self._combo.get_model()
		treeIter = model.get_iter_first()
		buffer = [self.text]
		toRemove = []
		# We're going to add the item at the top.
		required = self.LENGTH - 1
		while treeIter:
			value = model.get_value(treeIter, 0)
			if len(buffer) > required or value == self.text:
				toRemove.append(treeIter)
			else:
				buffer.append(value.encode(self._encoding))
			treeIter = model.iter_next(treeIter)
		for treeIter in toRemove:
			model.remove(treeIter)
		self._combo.prepend_text(self.text)
		open(self._filename, "w").write("%s\n" % "\n".join(buffer))

	def _get_text(self):
		return self._combo.get_active_text()
	def _set_text(self, text):
		self._combo.child.set_text(text)
	text = property(_get_text, _set_text, None, "Active text.")

	def grab_focus(self):
		"""
		Defer to the combo box.
		"""
		self._combo.grab_focus()

# End of $URL$
